$(function() {
  if (!$('body').hasClass('admin-products')) return;

  $('.ui.dropdown').dropdown();

  if ($('body').hasClass('admin-products-index')) {
    var innoawardId = gon.innoaward_id;
    var baseUrl = '/admin/innoawards/' + innoawardId + '/products';
    var products = gon.products;

    var results = new Vue({
      el: '#result',
      data: {
        products: products,
        innoawardId: innoawardId
      },
      watch: {
        products: function(){
          listenChoiceModal();
        }
      },
      methods: {
        approve: function(id, stat, index){
          $.ajax({
            url: baseUrl + '/' + id + '/approve?status=' + stat,
            method: 'patch',
            success: function(data) {
              results.products.$set(index, data);
            }
          });
        }
      }
    });

    var searchInput = new Vue({
      el: '#search-input',
      data: {
        query: ''
      },
      methods: {
        submit: function(){
          $.get(baseUrl + '/search?query=' + this.query, function(res, status){
            $('#result').find('tr').remove();
            results.products = res.products;
            $('nav.pagination').remove();
          });
        }
      }
    });

    function listenChoiceModal() {
      // 参选按钮
      var $choosen = $('.choosen');

      $choosen.on('click', function(){
        var $choosenModal = $('#choosen-modal');
        $choosenModal.find('#rank_product_id').val($(this).data('proId'));
        $('#choosen-modal').modal('show');
      });
    }

    listenChoiceModal();

    // 参选modal提交
    var $rankSubmit = $('#rankSubmit');

    $rankSubmit.on('click', function(){
      $('#rankForm').submit();
    });
  }

  if ($('body').hasClass('admin-products-edit') || $('body').hasClass('admin-products-new')) {
    $('#logo-input').change(function(){
      if (this.files && this.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
          $('#logo-preview').attr('src', e.target.result);
        }
        reader.readAsDataURL(this.files[0]);
      }
    });

    $('#screenshots-input').change(function() {
      var preview = $('#screenshots-preview');
      var files = this.files;
      if (files) {
        preview.find('img').remove();
        for(var i = 0; i < files.length; i++) {
          var reader = new FileReader();
          var file = files[i];
          reader.onload = function(e) {
            preview.append('<img src="' + e.target.result + '" height="200">');
          }
          reader.readAsDataURL(file);
        };
      }
    });
  }
});
